<template>
  <div class="form-box">
    <el-form ref="ruleForm" :rules="rules" :model="itemInfo" label-width="auto">
      <el-form-item label="设置背景图：">
        <el-radio-group v-model="itemInfo.background">
          <el-radio
            v-for="item in backgroundType"
            :key="item.value"
            :label="item.value"
            >{{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="itemInfo.background === 'pureColour'">
        <el-color-picker v-model="itemInfo.color" show-alpha> </el-color-picker>
      </el-form-item>
      <el-form-item
        v-if="itemInfo.background === 'backgroundImg'"
        prop="backgroundImg"
      >
        <uploadSingImg
          :imgUrl="itemInfo.backgroundImg"
          accept=".jpg,.jpeg,.png"
          :maxSize="10"
          @getImgUrl="getBackgroundImg"
        >
          <template v-slot:imgInfo>
            (建议上传图片尺寸 宽750px, png jpg格式,尺寸最大10M)
          </template>
        </uploadSingImg>
      </el-form-item>
      <el-form-item label="选择视频：" prop="videoUrl">
        <el-upload
          action="#"
          class="avatar-uploader"
          :http-request="() => {}"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :accept="accept"
        >
          <video
            controls
            class="avatar"
            v-if="itemInfo.videoUrl"
            :src="itemInfo.videoUrl"
            :poster="`${itemInfo.videoUrl}?x-oss-process=video/snapshot,t_2000,h_200,m_fast`"
          ></video>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          <div slot="tip" class="el-upload__tip">
            上传视频不能超过50M<br />
            支持 MP4、WebM、Ogg 格式
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="选择视频封面：" prop="cover">
        <uploadSingImg
          :imgUrl="itemInfo.cover"
          accept=".jpg,.jpeg,.png"
          :maxSize="10"
          @getImgUrl="getCover"
        >
          <template v-slot:imgInfo>
            (建议上传图片尺寸 宽640px, png jpg格式,尺寸最大10M)
          </template>
        </uploadSingImg>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import uploadSingImg from '@common/uploadSingImg'
import { getOssKey } from '@utils/countDownload'
export default {
  props: ['itemInfo'],
  components: { uploadSingImg },
  data() {
    return {
      accept: '.mp4,.webm,.ogg',
      backgroundType: [
        { label: '纯色', value: 'pureColour' },
        { label: '背景图', value: 'backgroundImg' }
      ],
      rules: {
        backgroundImg: [
          { required: true, message: '请上传背景图', trigger: 'change' }
        ],
        cover: [{ required: true, message: '请上传封面图', trigger: 'change' }],
        videoUrl: [{ required: true, message: '请上传视频', trigger: 'change' }]
      }
    }
  },
  mounted() {},
  methods: {
    /* 视频位背景图 */
    getBackgroundImg(url) {
      this.itemInfo.backgroundImg = url
      this.$refs['ruleForm'].validateField('backgroundImg')
    },
    /* 视频封面图 */
    getCover(url) {
      this.itemInfo.cover = url
      this.$refs['ruleForm'].validateField('cover')
    },
    /* 上传视频 */
    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.'))
      if (this.accept.indexOf(fileSuffix) === -1) {
        this.$message.warning(`不支持上传${fileSuffix}类型视频`)
        return false
      }
      if (file.size / 1024 / 1024 > 50) {
        this.$message.error('视频最大不能超过50M')
        return
      }
      this.submitUpload(file)
    },
    submitUpload(file) {
      let _this = this
      let loading = this.$loading({
        lock: true,
        text: '上传中……',
        background: 'rgba(0, 0, 0, 0.7)',
        target: '.el-upload'
      })
      const bucketName =
        process.env.VUE_APP_ENV === 'testENV'
          ? 'dapeng-test-image'
          : 'dapeng-image'
      const date = this.moment(new Date().getTime()).format('YYYY-MM-DD')
      const userId = this.$store.state.user.dapengUserId
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.'))
      getOssKey({}, (res) => {
        const client = new OSS({
          region: 'oss-cn-beijing',
          accessKeyId: res.accessKeyId,
          accessKeySecret: res.accessKeySecret,
          stsToken: res.securityToken,
          bucket: bucketName
        })
        const uploadUrl = `${date}/${userId}/${new Date().getTime()}_T1BFUkFURQ==${fileSuffix}`
        async function put() {
          try {
            await client.put(uploadUrl, file)
            _this.itemInfo.videoUrl = `${process.env.VUE_APP_OSS_URL}${uploadUrl}`
            loading.close()
            _this.$refs['ruleForm'].validateField('videoUrl')
          } catch (e) {
            _this.$message.error('上传失败')
            loading.close()
          }
        }
        put()
      })
    },
    /* 收集数据 */
    collectData() {
      let flag = false
      const { background, backgroundImg } = this.itemInfo
      this.itemInfo.backgroundImg =
        background === 'pureColour' ? '' : backgroundImg
      this.$refs['ruleForm'].validate((valid) => {
        flag = valid ? true : false
      })
      return flag ? this.itemInfo : false
    }
  }
}
</script>
<style lang="less">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 200px;
  line-height: 200px;
  text-align: center;
}
.el-upload__tip {
  line-height: 16px;
  color: #f00;
  margin-top: 0;
}
.avatar {
  width: 200px;
  height: 200px;
  display: block;
}
</style>
